/* eslint-disable no-nested-ternary */
import React from 'react';
import {Spin, Card, Button, Row, Col, Form, Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, DATETIME_FORMAT} from '../constants';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {confirmData, upInvoiceData, invoiceConfirmData, writeOffData, getDetail} from './api';
import TextInput from 'Shared/components/TextInput';
import {currency, marketingActivityMainItem} from '../Enum';
import TagSelect from 'Shared/components/TagSelect';
import {injectIntl, language} from './intl';
import styles from './style.css';
import Return from '../common/Return';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import FileUpload from './FileUpload';
const EMPTY_ARRAY = [];
const {Description} = DescriptionList;
const FormItem = Form.Item;

const marketingActivityMainItemToList = marketingActivityMainItem.toList(language);
class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {
            attachmentInvoices: []
        },
        planItemDetails: [],
        actualItemDetails: [],
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            planItemDetails: res.data.planItemDetails,
                            actualItemDetails: res.data.actualItemDetails,
                        });
                    else
                        this.setState({loading: false});
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const confirmCondition = {
            confirmComment: data.confirmComment,
            rowVersion: data.rowVersion,
        };
        const upInvoiceCondition = {
            uploadComment: data.uploadComment,
            rowVersion: data.rowVersion,
            attachmentInvoices: data.attachmentInvoices === undefined ? '' : data.attachmentInvoices.map(v => ({
                fileId: v.fileId,
                fileName: v.fileName
            }))
        };
        const invoiceConfirmCondition = {
            invoiceComment: data.invoiceComment,
            rowVersion: data.rowVersion,
        };
        const writeOffCondition = {
            writeOffComment: data.writeOffComment,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        if(this.props.page === 'confirm')
            confirmData(this.props.id, confirmCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else if(this.props.page === 'upInvoice')
            upInvoiceData(this.props.id, upInvoiceCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else if(this.props.page === 'invoiceConfirm')
            invoiceConfirmData(this.props.id, invoiceConfirmCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else if(this.props.page === 'writeOff')
            writeOffData(this.props.id, writeOffCondition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachmentInvoices.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachmentInvoices = data.attachmentInvoices || [];
        attachmentInvoices.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachmentInvoices
            },
            hasOperat: true,
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachmentInvoices = data.attachmentInvoices || [];
        attachmentInvoices.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachmentInvoices
            },
            hasOperat: true,
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, planItemDetails, actualItemDetails, attachmentPresentations = [], loading} = this.state;
        const {isDealerUser} = this.props;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const planItemDetailColumns = [{
            title: formatMessage({
                id: 'approvePanel.column.num',
                defaultMessage: '序号'
            }),
            dataIndex: 'num',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.marketingActivityItemCategoryL1Name',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'marketingActivityItemCategoryL1Name',
            render: (text, record) => `${text}/${record.marketingActivityItemCategoryL2Name}`
        }, {
            title: formatMessage({
                id: 'approvePanel.column.item',
                defaultMessage: '项目'
            }),
            dataIndex: 'item',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.amount',
                defaultMessage: '费用'
            }),
            dataIndex: 'amount',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.address',
                defaultMessage: '网址'
            }),
            dataIndex: 'address',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.posts',
                defaultMessage: '发帖量'
            }),
            dataIndex: 'posts',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.reading',
                defaultMessage: '阅读量'
            }),
            dataIndex: 'reading',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.traffic',
                defaultMessage: '点击量'
            }),
            dataIndex: 'traffic',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.likes',
                defaultMessage: '点赞量'
            }),
            dataIndex: 'likes',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.commentVolume',
                defaultMessage: '评论量'
            }),
            dataIndex: 'commentVolume',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.forwardingVolume',
                defaultMessage: '转发量'
            }),
            dataIndex: 'forwardingVolume',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.remark',
                defaultMessage: '其它'
            }),
            dataIndex: 'remark',
        }];
        const actualItemDetailColumns = [{
            title: formatMessage({
                id: 'approvePanel.column.num',
                defaultMessage: '序号'
            }),
            dataIndex: 'num',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.marketingActivityItemCategoryL2Name',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'marketingActivityItemCategoryL2Name',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.item',
                defaultMessage: '项目'
            }),
            dataIndex: 'item',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.amount',
                defaultMessage: '费用'
            }),
            dataIndex: 'amount',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.address',
                defaultMessage: '网址'
            }),
            dataIndex: 'address',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.posts',
                defaultMessage: '发帖量'
            }),
            dataIndex: 'posts',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.reading',
                defaultMessage: '阅读量'
            }),
            dataIndex: 'reading',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.traffic',
                defaultMessage: '点击量'
            }),
            dataIndex: 'traffic',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.likes',
                defaultMessage: '点赞量'
            }),
            dataIndex: 'likes',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.commentVolume',
                defaultMessage: '评论量'
            }),
            dataIndex: 'commentVolume',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.forwardingVolume',
                defaultMessage: '转发量'
            }),
            dataIndex: 'forwardingVolume',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.remark',
                defaultMessage: '其它'
            }),
            dataIndex: 'remark',
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '营销活动报告信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.upInvoice}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.brandCode}){data.brandName}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.data.marketingActivityId',
                                        defaultMessage: '营销活动编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.marketingActivityCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                {!isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.data.dealerCode',
                                        defaultMessage: '总代编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.theme',
                                        defaultMessage: '主题'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.theme}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.statDate',
                                        defaultMessage: '开始时间'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.statDate, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.endDate',
                                        defaultMessage: '结束时间'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.endDate, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approvePanel.operation.mainItem',
                                        defaultMessage: '计划主项目'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TagSelect
                                            name="mainItem"
                                            value={data.mainItem || []}
                                            options={marketingActivityMainItemToList}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            {!data.mainItem || <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.mainItemRemark',
                                        defaultMessage: '计划主项目备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.mainItemRemark}
                                    </FormItem>
                                </Col>
                            </Row>}
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'approvePanel.operation.actualMainItem',
                                        defaultMessage: '实际主项目'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TagSelect
                                            name="actualMainItem"
                                            value={data.actualMainItem || []}
                                            options={marketingActivityMainItemToList} />
                                    </FormItem>
                                </Col>
                            </Row>
                            {!data.actualMainItem || <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.actualMainItemRemark',
                                        defaultMessage: '实际主项目备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.actualMainItemRemark}
                                    </FormItem>
                                </Col>
                            </Row>}
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.scope',
                                        defaultMessage: '营销目标'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.scope}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.confirmComment',
                                        defaultMessage: '确认意见'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {this.props.page === 'confirm' ? <TextInput
                                            name="confirmComment"
                                            type="textarea"
                                            value={data.confirmComment}
                                            onBlur={this.onChange} /> : data.confirmComment}
                                    </FormItem>
                                </Col>
                            </Row>
                            {this.props.page === 'confirm' || <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.uploadComment',
                                        defaultMessage: '上传意见'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {this.props.page === 'upInvoice' ? <TextInput
                                            name="uploadComment"
                                            type="textarea"
                                            value={data.uploadComment}
                                            onBlur={this.onChange} /> : data.uploadComment}
                                    </FormItem>
                                </Col>
                            </Row>}
                            {(this.props.page === 'confirm' || this.props.page === 'upInvoice') || <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.invoiceComment',
                                        defaultMessage: '发票确认意见'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {this.props.page === 'invoiceConfirm' ? <TextInput
                                            name="invoiceComment"
                                            type="textarea"
                                            value={data.invoiceComment}
                                            onBlur={this.onChange} /> : data.invoiceComment}
                                    </FormItem>
                                </Col>
                            </Row>}
                            {this.props.page === 'writeOff' && <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.writeOffComment',
                                        defaultMessage: '核销意见'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {this.props.page === 'writeOff' ? <TextInput
                                            name="writeOffComment"
                                            type="textarea"
                                            value={data.writeOffComment}
                                            onBlur={this.onChange} /> : data.writeOffComment}
                                    </FormItem>
                                </Col>
                            </Row>}
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.summarize',
                        defaultMessage: '活动总结'
                    })}>
                        <Form>
                            <Row className="row-margin">
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.customerQTY',
                                        defaultMessage: '目标用户量'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.customerQTY}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.amount',
                                        defaultMessage: '计划费用'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.amount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.actualCustomerQTY',
                                        defaultMessage: '实际用户量'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.actualCustomerQTY}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.totalFee',
                                        defaultMessage: '实际费用'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.totalFee}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.actualSituation',
                                        defaultMessage: '完成情况'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.actualSituation}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.opinion',
                                        defaultMessage: '改善意见'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.opinion}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.planItemDetails',
                            defaultMessage: '活动计划项目清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={planItemDetailColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={planItemDetails}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.actualItemDetails',
                            defaultMessage: '活动实际项目清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={actualItemDetailColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={actualItemDetails}
                            {...TABLE} />
                    </Card>
                    {attachmentPresentations && attachmentPresentations.length >= 0
                        ? <Card><DescriptionList size="large" title={formatMessage({
                            id: 'approvePanel.card.attachmentPresentations',
                            defaultMessage: '报告附件'
                        })}>
                            {attachmentPresentations.map(item => (<Description key={item.id}>
                                <a onClick={this.onClickDownload} key="delete" data-id={item.filePath} data-applyid={item.fileName}>
                                    {item.fileName}</a></Description>))}
                        </DescriptionList></Card>
                        : <Card><DescriptionList size="large" title={formatMessage({
                            id: 'approvePanel.content.noAttachment',
                            defaultMessage: '暂无附件'
                        })}>
                        </DescriptionList></Card>}
                    {this.props.page === 'upInvoice' ? <Card title={formatMessage({
                        id: 'approvePanel.title.files',
                        defaultMessage: '发票附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachmentInvoices || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card> : this.props.page === 'invoiceConfirm' || this.props.page === 'writeOff'
                        ? data.attachmentInvoices && data.attachmentInvoices.length >= 0
                            ? <Card><DescriptionList size="large" title={formatMessage({
                                id: 'approvePanel.card.attachmentInvoices',
                                defaultMessage: '发票附件清单'
                            })}>
                                {data.attachmentInvoices.map(item => (<Description key={item.id}>
                                    <a onClick={this.onClickDownload} key="delete" data-id={item.filePath} data-applyid={item.fileName}>
                                        {item.fileName}</a></Description>))}
                            </DescriptionList></Card>
                            : <Card><DescriptionList size="large" title={formatMessage({
                                id: 'approvePanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList></Card> : ''}
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
